package com.basic.business;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.*;

public class FileProcessingSystem {
    private final ExecutorService executor = Executors.newCachedThreadPool();
    private final ConcurrentMap<String, Future<?>> fileTasks = new ConcurrentHashMap<>();

    // 主线程获取数据并启动文件生成任务
    public void processDataAndGenerateFile(String taskId, String data) {
        // 存储数据到数据库（模拟）
        storeToDatabase(taskId, data);

        // 提交文件生成任务
        Future<?> future = executor.submit(() -> {
            try {
                generateFile(taskId);
            } catch (InterruptedException e) {
                handleTaskCancellation(taskId);
                Thread.currentThread().interrupt();
            }
        });

        fileTasks.put(taskId, future);
    }

    // 取消文件生成任务
    public void cancelFileGeneration(String taskId) {
        Future<?> future = fileTasks.get(taskId);
        if (future != null) {
            future.cancel(true); // 中断执行
            fileTasks.remove(taskId);
            System.out.println("任务已取消: " + taskId);
        }
    }

    // 生成文件（包含中断检查）
    private void generateFile(String taskId) throws InterruptedException {
        File file = new File(taskId + ".txt");
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            for (int i = 0; i < 10; i++) {
                // 显式检查中断
                if (Thread.currentThread().isInterrupted()) {
                    throw new InterruptedException("任务被取消");
                }

                // 模拟文件写入操作
                writer.write("Data block " + i);
                writer.newLine();
                Thread.sleep(500); // 可中断的阻塞操作
            }
            System.out.println("文件生成完成: " + taskId);
        } catch (IOException | InterruptedException e) {
            if (e instanceof InterruptedException) {
                System.out.println("中断文件生成: " + taskId);
                file.delete(); // 清理部分文件
                throw (InterruptedException) e;
            }
            e.printStackTrace();
        }
    }

    // 数据库存储（模拟）
    private void storeToDatabase(String taskId, String data) {
        System.out.println("存储到数据库: " + taskId + " -> " + data);
    }

    // 任务取消后的处理
    private void handleTaskCancellation(String taskId) {
        System.out.println("执行清理操作: " + taskId);
    }

    // 关闭线程池
    public void shutdown() {
        executor.shutdown();
    }

    public static void main(String[] args) throws InterruptedException {
        FileProcessingSystem system = new FileProcessingSystem();

        // 模拟正常流程
        system.processDataAndGenerateFile("task1", "sample-data");

        // 模拟取消操作
        new Thread(() -> {
            try {
                Thread.sleep(2000); // 等待2秒后取消
                system.cancelFileGeneration("task1");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}